﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using UncleBobWebService.Models;
using UncleBobWebService.ServiceRequester;
using UncleBobApplicantWebService;
using UncleBobWebService.Database;


namespace UncleBobApplicantWebService.Controllers
{
    public class StaffingExpertMenuController : Controller
    {
        //----------------------------------------------
        //----------------------------------------------
        private UncleBobApplicantWebService.ApplicantWebService.WebServiceClient mApplicantClient = new UncleBobApplicantWebService.ApplicantWebService.WebServiceClient();
        private UncleBobApplicantWebService.StaffWebService.WebServiceClient mStaffClient = new UncleBobApplicantWebService.StaffWebService.WebServiceClient();
        private Message msg;


        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        //Display views
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        /// <summary>
        /// Display Staffing Expert Main Menu view page
        /// </summary>
        /// <returns></returns>
        public ActionResult StaffingExpertMainMenu()
        {
            return View((RegisterModel)Session[SessionKeys.USER]);
        }


        /// <summary>
        /// Display all jobs view page
        /// </summary>
        /// <returns></returns>
        public ActionResult JobsListView()
        {
            return View((List<JobModel>)Session[SessionKeys.JOBSLIST]);
        }


        /// <summary>
        /// Display create new job view page
        /// </summary>
        /// <param name="id">Job ID need to editting, otherwise null</param>
        /// <returns></returns>
        public ActionResult CreateNewQuestion()
        {
            return View();
        }

        //**************************************************
        //Display create new job view
        //**************************************************
        public ActionResult CreateNewJob(string id)
        {
            if (id != null)
            {
                foreach (JobModel job in (List<JobModel>)Session[SessionKeys.JOBSLIST])
                {
                    if (string.Compare(job.ID.ToString(), id) == 0)
                    {
                        Session.Remove(SessionKeys.JOB);
                        Session.Add(SessionKeys.JOB, job);
                    }
                }

                Session.Remove(SessionKeys.JOBSLIST);
                return View(Session[SessionKeys.JOB] as JobModel);
            }
            else
            {
                Session.Add(SessionKeys.JOB, new JobModel());
            }

            return View();
        }

        /// <summary>
        /// Display Multiple Choice Question view page
        /// </summary>
        /// <param name="id">Question ID for editting, otherwise null</param>
        /// <returns></returns>
        public ActionResult MultipleChoiceQuestion(string id)
        {
            MultipleChoiceQuestion question = null;
            ApplicationQuestions qList = Session[SessionKeys.QUESTIONS] as ApplicationQuestions;

            if (id == null)
            {
                id = Session[SessionKeys.EXTRA] as string;
                Session.Remove(SessionKeys.EXTRA);
            }

            foreach (ApplicationQuestion ques in qList.Questions)
            {
                if (string.Compare(ques.QuestionID.ToString(), id) == 0)
                    question = ques as MultipleChoiceQuestion;
            }

            if (qList.Questions.Count != 0 && qList.Questions.Last().QuestionID == 0)
                question = qList.Questions.Last() as MultipleChoiceQuestion;
            else
            {
                if (question == null)
                {
                    question = new MultipleChoiceQuestion();
                    qList.AddQuestion(question);
                }
            }
                
            return View(question);
        }


        /// <summary>
        /// Display Create Extended Question view page
        /// </summary>
        /// <param name="id">Question ID for editting, otherwise null</param>
        /// <returns></returns>
        public ActionResult ExtendedQuestion(string id)
        {
            ExtendedQuestion question = null;
            ApplicationQuestions qList = Session[SessionKeys.QUESTIONS] as ApplicationQuestions;

            if (id == null)
            {
                id = Session[SessionKeys.EXTRA] as string;
                Session.Remove(SessionKeys.EXTRA);
            }

            foreach (ApplicationQuestion ques in qList.Questions)
            {
                if (string.Compare(ques.QuestionID.ToString(), id) == 0)
                    question = ques as ExtendedQuestion;
            }

            if (qList.Questions.Count != 0 && qList.Questions.Last().QuestionID == 0)
                question = qList.Questions.Last() as ExtendedQuestion;
            else
            {
                if (question == null)
                {
                    question = new ExtendedQuestion();
                    qList.AddQuestion(question);
                }
            }

            return View(question);
        }



        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        //Handle form in views
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        /// <summary>
        /// Handle form action in Staffing Expert Main Menu view page
        /// </summary>
        /// <param name="collection"></param>
        /// <returns>Return to login page when done</returns>
        public ActionResult FormAction(FormCollection collection)
        {
            /// Staffing Expert create new job
            if (collection["createJob"] != null)
            {
                return RedirectToAction("CreateNewJob", "StaffingExpertMenu");
            }            

            /// Display all jobs, Staffing Expert chooses job needed editting
            else if (collection["editJob"] != null)
            {
                CreateMessage(MessageTypes.SERVICE_GET_ALL_JOBS);
                msg = mApplicantClient.RequestService(msg);

                switch (msg.Result)
                {
                    case true:
                        List<JobModel> list = msg.Data as List<JobModel>;
                        Session.Add(SessionKeys.JOBSLIST, msg.Data as List<JobModel>);
                        return RedirectToAction("JobsListView", "StaffingExpertMenu");

                    case false:
                        return RedirectToAction("Error", "Error");
                }
            }

            Session.Clear();
            return RedirectToAction("Index", "Welcome");
        }


        /// <summary>
        /// Handle form action in Jobs List view page
        /// </summary>
        /// <param name="collection"></param>
        /// <returns>Return to Staffing Expert Main Menu when done</returns>
        public ActionResult JobListFormAction(FormCollection collection)
        {
            if (string.Compare(Session[SessionKeys.ACCESSLEVEL].ToString(), PermissionTypes.User.HiringManager.ToString()) == 0)
            {
                return RedirectToAction("MainMenu", "HMMainMenu");
            }
            
            return RedirectToAction("StaffingExpertMainMenu", "StaffingExpertMenu");
        }


        /// <summary>
        /// Handle form action in Create/Edit Job view page
        /// </summary>
        /// <param name="collection"></param>
        /// <returns>Return to Staffing Expert Main Menu when done</returns>
        public ActionResult CreateJobFormAction(FormCollection collection)
        {
            if (collection["cmdQuestions"] != null)
            {
                // View                Folder
                return RedirectToAction("QuestionsMenu", "QuestionsMenu");
            }
            if (collection["cmdSubmit"] != null)
            {
                JobModel job = Session[SessionKeys.JOB] as JobModel;

                job.Title = collection.Get("txtTitle");
                job.PositionsAvailable = int.Parse(collection.Get("txtPositions"));
                job.Location = collection.Get("txtLocation");
                job.Salary = collection.Get("txtSalary");
                job.Description = collection.Get("txtDescription");

                /// Edit existing job
                if (((JobModel)(Session[SessionKeys.JOB])).ID != 0)
                {
                    JobModel tmp = Session[SessionKeys.JOB] as JobModel;
                    Message msg = new Message();
                    msg.Data = job;
                    msg.Category = MessageTypes.SERVICE_EDIT_EXISTING_JOB;

                    try
                    {
                        msg = mApplicantClient.RequestService(msg);
                    }
                    catch (Exception ex)
                    {
                        msg.Extra = ex.Message;
                        msg.Result = false;
                    }
                    //Session.Add(SessionKeys.QUESTIONS, job.QuestionsList);
                }

                /// Create new job
                else
                {
                    Session.Add(SessionKeys.JOB, job);
                    Message msg = new Message();
                    msg.Data = job;
                    msg.Category = MessageTypes.SERVICE_ADD_NEW_JOB;                    

                    try
                    {
                        msg = mApplicantClient.RequestService(msg);
                    }
                    catch (Exception ex)
                    {
                        msg.Extra = ex.Message;
                        msg.Result = false;
                    }
                    //Session.Add(SessionKeys.QUESTIONS, new ApplicationQuestions());
                }

                //return RedirectToAction("CreateQuestions", "StaffingExpertMenu");
            }

            if (string.Compare(Session[SessionKeys.ACCESSLEVEL].ToString(), PermissionTypes.User.HiringManager.ToString()) == 0)
            {
                return RedirectToAction("MainMenu", "HMMainMenu");
            }

            return RedirectToAction("StaffingExpertMainMenu", "StaffingExpertMenu");
        }


        /// <summary>
        /// Handle form action in Create/Display/Edit Questions page
        /// </summary>
        /// <param name="collection"></param>
        /// <returns>Back to Staffing Expert Main Menu when done</returns>
        public ActionResult CreateQuestionFormAction(FormCollection collection)
        {
            //+++++++++++++++++++++++++++++++++++++++++
            //Need to implement when staffing expert want to edit a question
            //+++++++++++++++++++++++++++++++++++++++++    
            ApplicationQuestions questionList = Session["Questions"] as ApplicationQuestions;

            /// Create Multiple Choices Question
            if (collection["cmdMulti"] != null)
            {
                return RedirectToAction("MultipleChoiceQuestion", "StaffingExpertMenu");
            }

            /// Create Extended Question
            if (collection["cmdExtended"] != null)
            {
                return RedirectToAction("ExtendedQuestion", "StaffingExpertMenu");
            }

            if (string.Compare(Session[SessionKeys.ISEDIT] as string, "Edit") == 0)
            {

            }
            else
            {
                JobModel job = Session[SessionKeys.JOB] as JobModel;
                job.QuestionsList = questionList;
                CreateMessage(MessageTypes.SERVICE_REGISTER_NEW_USER, job);
                msg = mStaffClient.RequestService(msg);
            }

            return RedirectToAction("StaffingExpertMainMenu", "StaffingExpertMenu");
        }


        /// <summary>
        /// Handle form action in Create/Edit multiple choices question
        /// </summary>
        /// <param name="collection"></param>
        /// <returns>Back to Create Question pages when success, ortherwise, stay on current page to fix error</returns>
        public ActionResult MultipleChoicesFormAction(FormCollection collection)
        {
            ApplicationQuestions qList = Session[SessionKeys.QUESTIONS] as ApplicationQuestions;
            MultipleChoiceQuestion question = qList.Questions.Last() as MultipleChoiceQuestion;

            int index = question.PossibleAnswers.Count;
            int questionID = 0;
            string questionTitle = collection["Question"];
            string value = collection["btnRadio"];

            if (collection["cmdCancel"] == null)
            {
                /// Check if ID is not numeric
                try
                {
                    questionID = Convert.ToInt32(collection["QuestionID"]);
                }
                catch (Exception)
                {                   
                    Session.Remove(SessionKeys.ERROR);
                    Session.Add(SessionKeys.ERROR, "ID is not numeric");
                    return RedirectToAction("MultipleChoiceQuestion", "StaffingExpertMenu");
                }

                /// Check if ID is zero and question are missing, otherwise, record ID and question
                if (questionID == 0 || questionTitle == "" || questionTitle == " ")
                {
                    Session.Add(SessionKeys.ERROR, "ID/Question is missing");
                    return RedirectToAction("MultipleChoiceQuestion", "StaffingExpertMenu");
                }
                else
                {
                    question.QuestionID = questionID;
                    question.Question = questionTitle;
                }

                /// Add answers to question
                for (int i = 0; i <= index; ++i)
                    if (collection[i.ToString()] != null && collection[i.ToString()] != "" && collection[i.ToString()] != " ")
                    {
                        if (question.PossibleAnswers.ContainsKey(i))
                            question.PossibleAnswers[i].TheAnswer = collection[i.ToString()];
                        else
                            question.AddPossibleAnswer(new Answer(collection[i.ToString()], false));
                    }
                Session.Add(SessionKeys.EXTRA, collection["QuestionID"]);

                /// Submit button
                if (collection["cmdSubmit"] != null)
                {
                    if (value != null)
                    {
                        Session.Remove(SessionKeys.EXTRA);
                        question.PossibleAnswers[Convert.ToInt32(value)].IsCorrect = true;
                    }
                    else
                    {
                        Session.Add(SessionKeys.ERROR, "Correct answer is missing");
                        return RedirectToAction("MultipleChoiceQuestion", "StaffingExpertMenu");
                    }
                }

                /// Add Answer Button
                if (collection["cmdAddAnswer"] != null)
                {
                    return RedirectToAction("MultipleChoiceQuestion", "StaffingExpertMenu");
                }
            }
            else
            {
                qList.Questions.Remove(qList.Questions.Last());
            }

            return RedirectToAction("CreateQuestions", "StaffingExpertMenu");
        }


        /// <summary>
        /// Handle form action in Create/Edit extended question
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult ExtendedQuestionFormAction(FormCollection collection)
        {
            ApplicationQuestions qList = Session[SessionKeys.QUESTIONS] as ApplicationQuestions;
            ExtendedQuestion question = qList.Questions.Last() as ExtendedQuestion;

            int questionID = 0;
            string questionTitle = collection["Question"];

            if (collection["cmdCancel"] == null)
            {
                /// Check if ID is not numeric
                try
                {
                    questionID = Convert.ToInt32(collection["QuestionID"]);
                }
                catch (Exception error)
                {
                    Session.Remove(SessionKeys.ERROR);
                    Session.Add(SessionKeys.ERROR, "ID is not numeric");
                    return RedirectToAction("ExtendedQuestion", "StaffingExpertMenu");
                }

                /// Check if ID is zero and question are missing, otherwise, record ID and question
                if (questionID == 0 || questionTitle == "" || questionTitle == " ")
                {
                    Session.Add(SessionKeys.ERROR, "ID/Question is missing");
                    return RedirectToAction("ExtendedQuestion", "StaffingExpertMenu");
                }
                else
                {
                    question.QuestionID = questionID;
                    question.Question = questionTitle;
                }
            }
            else
            {
                qList.Questions.Remove(qList.Questions.Last());
            }

            return RedirectToAction("CreateQuestions", "StaffingExpertMenu");
        }


        /// <summary>
        /// Create requesting message
        /// </summary>
        /// <param name="category">Message Type</param>
        /// <param name="data">Data to transfer to service</param>
        /// <param name="extra">Extra field</param>
        private void CreateMessage(string category, Object data = null, string extra = null)
        {
            msg = new Message();
            msg.Category = category;
            msg.Data = data;
            msg.Extra = extra;
        }
    }
}
